package com.mkb.conf;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.mkb.common.WebConstant;
import com.mkb.entity.UserInfoDTO;
import com.mkb.utils.WinowUtil;
import com.zz.common.context.AdminContext;
import com.zz.common.domain.CompanyDepartment;
import com.zz.common.domain.Department;
import com.zz.common.enums.ManagerDegreeEnum;
import com.zz.common.result.ResultInfo;
import com.zz.common.utils.CookieUtil;
import com.zz.common.utils.JwtHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AdminLoginAuthInterceptor implements HandlerInterceptor {

    // 预处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUri = request.getRequestURI();
        //重复提交过滤
        if (!filterDuplicatesRequest(request, handler)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(JSONObject.toJSONString(ResultInfo.err("请勿重复操作")));
            return false;
        }

        // 判断是否不过滤的请求
        if (WebConstant.InherentEscapeURIS.contains(requestUri)) {
            return true;
        } else {
            UserInfoDTO context = getAdminContext(request);
            if (context == null) {
                if (WinowUtil.isWindows()){
                    response.sendRedirect(WebConstant.URL_WINOWS);
                }else {
                    response.sendRedirect(WebConstant.URL_LINUX);
                }

                return false;
            }
            return true;
        }
    }

    private Boolean filterDuplicatesRequest(HttpServletRequest request, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NotDuplicateRequest methodAnnotation = handlerMethod.getMethodAnnotation(NotDuplicateRequest.class);
            if (null == methodAnnotation) {
                return Boolean.TRUE;
            } else {
                StringBuffer requestURL = request.getRequestURL();
                String method = request.getMethod();
                String checkRequetKey = request.getSession().getId() + requestURL + method;
                return CacheUtils.setIfAbsent(checkRequetKey, "1", methodAnnotation.milliSecond(), TimeUnit.MILLISECONDS);
            }
        }
        return Boolean.TRUE;
    }


    public boolean checkAuth(AdminContext context, String requestUri) {
        if (ManagerDegreeEnum.MANAGER.getValue() == context.getDegree()
                || ManagerDegreeEnum.SUPER_MANAGER.getValue() == context.getDegree()) {
            return true;
        } else {
            List<String> openList = context.getMenuList();
            if (WebConstant.INTERCEPT_URIS.contains(requestUri)) {
                if (!openList.isEmpty() && openList.contains(requestUri)) {
                    return true;
                } else {
                    return false;
                }
            }
            return true;
        }

    }

    private UserInfoDTO getAdminContext(HttpServletRequest request) {
        if (null == request.getSession()){
            return null;
        }
        UserInfoDTO context = (UserInfoDTO) request.getSession().getAttribute(WebConstant.SESSION_CONTEXT_NAME);
        return context;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

}